#include <iostream>
#include <thread>
#include <Windows.h>
#include "Listener.h"

InputListener input_listener;

void InputListener::ListenInput() {
	// Install keyboard hook
	keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, nullptr, 0);
	if (keyboardHook == nullptr) {
		LOG(ERROR) << "Failed to install keyboard hook.";
		return;
	}
	// Install mouse hook
	mouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, NULL, 0);
	if (mouseHook == NULL)
	{
		LOG(ERROR) << "Failed to install mouse hook.";
		return;
	}

	// Message loop
	MSG msg;
	while (GetMessage(&msg, nullptr, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	Unhook();
}

void InputListener::StartListening() {
	if (listeningThread.joinable()) {
		LOG(ERROR) << "Listening thread is already running.";
		return;
	}
	listeningThread = std::thread(&InputListener::ListenInput, this);
}

void InputListener::StopListening() {
	if (listeningThread.joinable()) {
		listeningThread.join();
	}
}

void InputListener::Unhook() {
	if (keyboardHook != nullptr) {
		UnhookWindowsHookEx(keyboardHook);
		keyboardHook = nullptr;
	}
	if (mouseHook != nullptr) {
		UnhookWindowsHookEx(mouseHook);
		mouseHook = nullptr;
	}
}
